package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.OrdersClient;
import com.robot.admin.pojo.client.SubOrders;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersClient ordersClient;
    @Autowired
    private HttpServletRequest request;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 所有订单并分页
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "{page}/{size}", method = RequestMethod.POST)
    public Result thirdFindSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(ordersClient.thirdFindSubOrdersBySearch(searchMap, page, size)));
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public Result findOrderById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId() + ", orders'id=" + id);
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        SubOrders subOrdersInDb = JSON.parseObject(ordersClient.thirdFindSubOrderById(id), SubOrders.class);
        logger.info("subOrdersInDb=" + subOrdersInDb);
        String message = checkPojo(subOrdersInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, subOrdersInDb);
    }

    /**
     * 检查实体类是否存在
     *
     * @param subOrdersInDb
     * @return
     */
    public String checkPojo(SubOrders subOrdersInDb) {
        if (subOrdersInDb == null) {
            return ("该订单不存在");
        }
        if (subOrdersInDb.getDeletedAt() != null) {
            return ("该订单已被删除");
        }
        return "";
    }
}
